package com.lazyframework.security.admin.authentication.filter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 考虑到前后端分离的模式下，一般都会将Content-Type设置为application/json，
 * 而SpringSecurity的FormLogin默认的Content-Type是x-www-form-urlencoded。此过滤器用于提取JSON请求的username、password参数
 *
 * Create by lazy in 2019.09.17
 */
public class UsernamePasswordObtainFilter extends OncePerRequestFilter {

    private RequestMatcher requiresAuthenticationRequestMatcher;

    private static final String[] JSON_CONTENT_RULES = {"application/json", "application/json;charset=UTF-8"};

    public UsernamePasswordObtainFilter(String loginProcessUrl) {
        this.requiresAuthenticationRequestMatcher = new AntPathRequestMatcher(loginProcessUrl, "POST");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        if (requiresAuthentication(request) && contentTypeIsJSON(request)) {
            Map<String, String> parameters = new ObjectMapper().readValue(request.getInputStream(),
                    new TypeReference<Map<String, String>>() {});
            request.getParameterMap().forEach((k, v) -> parameters.put(k, v[0]));
            request = new UsernamePasswordAdapterRequestWrapper(request, parameters);
        }
        filterChain.doFilter(request, response);
    }

    private boolean contentTypeIsJSON(HttpServletRequest request) {
        String contentType = request.getContentType();
        for (String rule : JSON_CONTENT_RULES) {
            if (rule.equalsIgnoreCase(contentType)) return true;
        }
        return false;
    }

    private boolean requiresAuthentication(HttpServletRequest request) {
        return requiresAuthenticationRequestMatcher.matches(request);
    }

    static class UsernamePasswordAdapterRequestWrapper extends HttpServletRequestWrapper {

        private Map<String, String> parameterMap;

        private UsernamePasswordAdapterRequestWrapper(HttpServletRequest request, Map<String, String> parameterMap) {
            super(request);
            this.parameterMap = parameterMap;
        }

        @Override
        public String getParameter(String name) {
            return this.parameterMap.get(name);
        }
    }

}
